package com.example.cvte.config;

import cn.hutool.json.JSONUtil;
import com.example.cvte.util.ResultUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author 郝文雪
 * @date 2022/10/31 20:46
 * @Description 统一数据格式处理
 */
@ControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResultUtil result=new ResultUtil();
        result.setMsg("");
        result.setState(1);
        result.setData(body);
        if(body instanceof String ){
            return JSONUtil.toJsonStr(result);
        }
        if(body!=null){
            result.setState(200);
        }
        return result;
    }
}
